import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Empty, Form, Icon, Typography, message, Select } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import useDictionary from '@/hooks/useDictionary';
import FormContainer from './FormContainer';

const { Text } = Typography;

/**
 * 员工档案 - 语言能力列表
 */
const LanguagesSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: langList,
        remove: langListRemove,
        push: langListPush,
        getKey: langListGetKey,
        resetList: langListReset
    } = useDynamicList([]);
    // 字典数据
    const [langHearSpeakLevelOptions, getLangHearSpeakLevelText] = useDictionary('lang_hear_speak_level');
    const [langReadWriteLevelOptions, getLangReadWriteLevelText] = useDictionary('lang_read_write_level');
    const [langTypeOptions, getLangTypeText] = useDictionary('recruitTalentLangType');

    useEffect(() => {
        // 重置列表的值
        langListReset(formData.langList);
    }, [langListReset, formData.langList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('langList', { initialValue: formData.langList || [] });
    }, [formData.langList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            newList: langList.map((item, index) => {
                const key = langListGetKey(index);
                return {
                    entryPersonnelCode: formData.entryPersonnelCode,
                    langType: values.langType[key],
                    readWriteAbility: values.readWriteAbility[key],
                    listenSpeakAbility: values.listenSpeakAbility[key]
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        langListReset(formData.langList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (langList.length === 0) {
            langListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="语言能力"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className="dynamicList">
                    {langList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className="dynamicListContainer">
                        {langList.map((item, index) => (
                            <div key={langListGetKey(index)} className="dynamicListItem">
                                {editStatus && props.isEntryGuide && (
                                    <div className="dynamicListItemHeader">语言能力 {index + 1}</div>
                                )}
                                {editStatus && (
                                    <Icon
                                        onClick={() => langListRemove(index)}
                                        className="dynamicListClose"
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Form.Item label="语言类型">
                                    {editStatus ? (
                                        getFieldDecorator(`langType[${langListGetKey(index)}]`, {
                                            initialValue: item?.langType || undefined,
                                            rules: [{ required: true, message: '请选择语种' }]
                                        })(
                                            <Select placeholder="请选择语言类型">
                                                {langTypeOptions?.map(option => (
                                                    <Select.Option value={option.value} key={option.value}>
                                                        {option.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>{getLangTypeText(item?.langType || '--')}</Text>
                                    )}
                                </Form.Item>
                                <Form.Item label="听说能力">
                                    {editStatus ? (
                                        getFieldDecorator(`listenSpeakAbility[${langListGetKey(index)}]`, {
                                            initialValue: item?.listenSpeakAbility
                                                ? Number(item.listenSpeakAbility)
                                                : undefined
                                        })(
                                            <Select
                                                getPopupContainer={trigger => trigger.parentElement}
                                                placeholder="请选择"
                                            >
                                                {langHearSpeakLevelOptions?.map(option => (
                                                    <Select.Option value={Number(option.value)} key={option.value}>
                                                        {option.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>
                                            {getLangHearSpeakLevelText(item?.listenSpeakAbility?.toString()) || '--'}
                                        </Text>
                                    )}
                                </Form.Item>
                                <Form.Item label="读写能力">
                                    {editStatus ? (
                                        getFieldDecorator(`readWriteAbility[${langListGetKey(index)}]`, {
                                            initialValue: item?.readWriteAbility
                                                ? Number(item.readWriteAbility)
                                                : undefined
                                        })(
                                            <Select
                                                getPopupContainer={trigger => trigger.parentElement}
                                                placeholder="请选择"
                                            >
                                                {langReadWriteLevelOptions?.map(option => (
                                                    <Select.Option value={Number(option.value)} key={option.value}>
                                                        {option.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>
                                            {getLangReadWriteLevelText(item?.readWriteAbility?.toString()) || '--'}
                                        </Text>
                                    )}
                                </Form.Item>
                            </div>
                        ))}
                    </div>
                    {editStatus ? (
                        <Button className="dynamicListAddButton" block onClick={() => langListPush({})}>
                            +添加语言能力
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
LanguagesSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

LanguagesSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default LanguagesSection;
